package deng.ejb3.examples.simplecase;

import java.io.StringReader;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.xml.bind.JAXB;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Zemian Deng
 *
 */
@MessageDriven(
	messageListenerInterface = MessageListener.class,
	activationConfig = { 
		@ActivationConfigProperty(propertyName = "destination", propertyValue = Constants.CREATE_EMPLOYEE_QUEUE),
		@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
	}
)
public class CreateEmployeeMsgBean implements MessageListener {

	private static Logger logger = LoggerFactory.getLogger(CreateEmployeeMsgBean.class);
	
	//@EJB /** Default to look for CustomerDalBean/local in JNDI. */
	@EJB(beanName="CustomerDalBean/local")
	//@EJB(beanName="MyCustomerDalBean/local") /* Use explicit declared bean name. */
	//@EJB(beanName="MyCustomerDalBean/local-deng.ejb3.examples.simplecase.CustomerDal") /* Same as above in JBoss5
	//@EJB(mappedName="MyMappedCustomerDalBean")
	//@EJB(beanName="CustomerDalBean/local", mappedName="MyMappedCustomerDalBean")
	//@EJB(beanName="CustomerDalBeanX/local", mappedName="MyMappedCustomerDalBean") /* WORKS STILL!, so beanName has no effect as it deployed as CustomerDalBean/local still. */ 
	private EmployeeDalLocal employeeDalLocal;
	
	@Override
    public void onMessage(Message message) {
		logger.trace("Received message class: " + message.getClass());
				
		try {
			TextMessage textMsg = (TextMessage)message;
			String text = textMsg.getText();
			StringReader stringReader= new StringReader(text);
			Employee employee = JAXB.unmarshal(stringReader, Employee.class);
			logger.info("Unmarshalled customer from text msg: " + employee);
			
			employeeDalLocal.insertCustomer(employee);
			logger.debug("Customer saved: " + employee);
		} catch (JMSException e) {
			throw new RuntimeException("Failed to process JMS msg: " + message, e);
		}
    }
	
}
